// pages/personal/personal.js

//获取应用实例
const app = getApp()

Page({

    /**
     * 页面的初始数据
     */
    data: {
        userInfo: {},
        personalInfo: {
            donation: 0
        },
        yaa: true,
        showShouquan: false,
        canIUse: wx.canIUse('button.open-type.getUserInfo'),
        encryptedData:null,
        iv:null
    },
    //事件处理函数
    turnToAbout: function (value) {
        wx.navigateTo({
            url: './about/about'
        })
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onShow: function (options) {        
        let userInfo = wx.getStorageSync('userInfo');
        if (userInfo){
          this.setData({
            userInfo: userInfo,
            hasUserInfo: true
          })
          this.getDonation()
        }else{
          this.setData({
            showShouquan: true
          })
        }
    },
    //用户捐款金额
    getDonation(){
      let userId = wx.getStorageSync('userId');
      wx.request({
        url: getApp().globalData.api + '/a/wxinterface/wechatUser', //
        data: {
          userId: userId
        },
        header: {
          'content-type': 'application/json' // 默认值
        },
        success: res => {
          console.log(res)
          let money = res.data.obj.totalMoney
          this.setData({
            personalInfo: { donation: money }
          })
        }
      })
    },
    getUserInfo: function (e) {
      this.setData({
        showShouquan: false
      })
      let res = e.detail
      wx.setStorageSync('userInfo', res.userInfo)
      this.setData({
        userInfo: res.userInfo,
        hasUserInfo: true,
        encryptedData: res.encryptedData,
        iv: res.iv
      })
      setUser(this)
    },
    hidthis(){
      this.setData({
        showShouquan: false
      })
    }
})

function setUser(_this){
    wx.login({
        success: function (res) {
          console.log(res.code)
            if (res.code) {
                wx.request({
                    url: getApp().globalData.api + '/a/wxinterface/setUserInfo', //
                    data: {
                        js_code: res.code,
                        encryptedData: _this.data.encryptedData,
                        iv: _this.data.iv
                    },
                    header: {
                        'content-type': 'application/json' // 默认值
                    },
                    success: res => {
                      let userId = res.data.obj.userId
                      wx.setStorageSync('userId',userId)
                      _this.getDonation()
                    }
                })
            }
        }
    })
}